package com.zzy.demo.common.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;
import net.coobird.thumbnailator.geometry.Positions;

public class ImageReduce {
	/**
	 * 按照图片宽高比例进行缩放大小
	 * @param in 图片流
	 * @param widthLimit 宽度限制,非正数表示无限制
	 * @param heightLimit 高度限制，非正数表示无限制
	 * @param quality 图片质量，1f为原质量
	 * @param changJPGType 图片是否转换成jpg格式
	 * @return
	 */
	public static byte[] getImgWHScale(InputStream in,int widthLimit,int heightLimit,float quality,boolean changJPGType){
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			BufferedImage srcFile = ImageIO.read(in);
			if(srcFile==null){//为null表示非图片
				return null;
			}
			int w = srcFile.getWidth(null);
			int h = srcFile.getHeight(null);
			double bili;
			int width = 0;
			int height = 0;
			if(w>h){//图片宽度大于高度时，以宽度为基准进行比例缩放
				if(widthLimit<=0){//无宽度限制
					if(heightLimit>0&&h>heightLimit){//有高度限制且图片高度大于限制高度，需要图片大小缩放
						height = heightLimit;
						bili = height/(double)h;
						width = (int)(w*bili);
					}else{//不需要图片大小缩放
						width = w;
						height = h;
					}
				}else if(w>widthLimit){//图片宽度大于限制宽度，图片需要进行大小缩放
					width = widthLimit;
					bili = width/(double)w;
					height = (int)(h*bili);
				}else{//不需要图片大小缩放
					width = w;
					height = h;
				}
			}else{
				if(heightLimit<=0){//无高度限制
					if(widthLimit>0&&w>widthLimit){//有宽度限制且图片宽度大于限制宽度，需要图片大小缩放
						width = widthLimit;
						bili = width/(double)w;
						height = (int)(h*bili);
					}else{//不需要图片大小缩放
						width = w;
						height = h;
					}
				}else if(h>heightLimit){//图片高度大于限制高度，图片需要进行大小缩放
					height = heightLimit;
					bili = height/(double)h;
					width = (int)(w*bili);
				}else{//不需要图片大小缩放
					width = w;
					height = h;
				}
			}
			Builder<BufferedImage> builder = Thumbnails.of(srcFile);
			builder.size(width, height);
			if(changJPGType){//需要输出jpg格式图片
				builder.outputFormat("jpg");
			}
			builder.outputQuality(quality);
			builder.toOutputStream(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toByteArray();
	}
	/**
	 * 按照指定宽高大小缩放图片
	 * @param in 图片流
	 * @param width 图片宽度
	 * @param height 图片高度
	 * @param quality 图片质量，1f为原质量
	 * @param changJPGType 图片是否转换成jpg格式
	 * @return
	 */
	public static byte[] getImgNoWHScale(InputStream in,int width,int height,float quality,boolean changJPGType){
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			BufferedImage srcFile = ImageIO.read(in);
			if(srcFile==null){//为null表示非图片
				return null;
			}
			Builder<BufferedImage> builder = Thumbnails.of(srcFile);
			builder.size(width, height);
			if(changJPGType){
				builder.outputFormat("jpg");
			}
			builder.outputQuality(quality);
			builder.toOutputStream(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toByteArray();
	}
	/**
	 * 按照比例进行缩放图片
	 * @param in 图片流
	 * @param scale 缩放比例，1为原图比例
	 * @param quality 图片质量，1f为原质量
	 * @param changJPGType 图片是否转换为jpg格式
	 * @return
	 */
	public static byte[] getImgScale(InputStream in,double scale,float quality,boolean changJPGType){
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			BufferedImage srcFile = ImageIO.read(in);
			if(srcFile==null){//为null表示非图片
				return null;
			}
			Builder<BufferedImage> builder = Thumbnails.of(srcFile);
			builder.scale(scale);
			if(changJPGType){
				builder.outputFormat("jpg");
			}
			builder.outputQuality(quality);
			builder.toOutputStream(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toByteArray();
	}
	/**
	 * 按照图片质量进行缩放图片
	 * @param in 图片流
	 * @param quality 图片质量，1f为原图质量
	 * @param changJPGType 图片是否转换为jpg格式
	 * @return
	 */
	public static byte[] getImgQuality(InputStream in,float quality,boolean changJPGType){
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			BufferedImage srcFile = ImageIO.read(in);
			if(srcFile==null){//为null表示非图片
				return null;
			}
			Builder<BufferedImage> builder = Thumbnails.of(srcFile);
			if(changJPGType){
				builder.outputFormat("jpg");
			}
			builder.outputQuality(quality);
			builder.toOutputStream(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toByteArray();
	}
	/**
	 * 添加图片水印
	 * @param in 图片流
	 * @param position 水印位置，（1：顶部居左；2：顶部居中；3：顶部居右；4：中间居左；5：居中；6：中间居右；7：底部居左；8：底部居中；9：底部居右）
	 * @param filePath 水印路径
	 * @param alpha 水印透明度，（0.0~1.0,0.0完全透明，1.0完全不透明）
	 * @param changJPGType 图片是否转换为jpg格式
	 * @return
	 */
	public static byte[] getImgImageWaterMark(InputStream in,int position,String filePath,float alpha,boolean changJPGType){
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			BufferedImage srcFile = ImageIO.read(in);
			if(srcFile==null){//为null表示非图片
				return null;
			}
			Builder<BufferedImage> builder = Thumbnails.of(srcFile);
			if(changJPGType){
				builder.outputFormat("jpg");
			}
			Positions positions;
			if(position==1){//顶部居左
				positions = Positions.TOP_LEFT;
			}else if(position==2){//顶部居中
				positions = Positions.TOP_CENTER;
			}else if(position==3){//顶部居右
				positions = Positions.TOP_RIGHT;
			}else if(position==4){//中间居左
				positions = Positions.CENTER_LEFT;
			}else if(position==5){//居中
				positions = Positions.CENTER;
			}else if(position==6){//中间居右
				positions = Positions.CENTER_RIGHT;
			}else if(position==7){//底部居左
				positions = Positions.BOTTOM_LEFT;
			}else if(position==8){//底部居中
				positions = Positions.BOTTOM_CENTER;
			}else if(position==9){//底部居右
				positions = Positions.BOTTOM_RIGHT;
			}else{//居中
				positions = Positions.CENTER;
			}
			//图片水印
			builder.watermark(positions,ImageIO.read(new File(filePath)),alpha);
			builder.toOutputStream(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toByteArray();
	}
	/**
	 * 
	 * @param in  图片流
	 * @param content 文字内容
	 * @param top 文字水印与图片顶部的距离（像素），负数表示居中
	 * @param left 文字水印与图片左端的距离（像素），负数标识居中
	 * @param fontName 字体名称，如：宋体
	 * @param fontStyle 字体样式，如：粗体（Font.BOLD）、斜体（Font.ITALIC）
	 * @param fontSize 字体大小，单位像素
	 * @param color 字体颜色
	 * @param alpha 水印透明度，（0.0~1.0,0.0完全透明，1.0完全不透明）
	 * @param changJPGType 图片是否转换成jpg格式
	 * @param fileType 原图片格式
	 * @return
	 */
	public static byte[] getImgWordWaterMark(InputStream in,String content,int top,int left,String fontName,int fontStyle,int fontSize,Color color,float alpha,boolean changJPGType,String fileType){
		if(content==null||"".equals(content)){
			return null;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			BufferedImage srcFile = ImageIO.read(in);
			if(srcFile==null){//为null表示非图片
				return null;
			}
			int width = srcFile.getWidth(null);
			int height = srcFile.getHeight(null);
			Builder<BufferedImage> builder = Thumbnails.of(srcFile);
			builder.scale(1);
			//文字水印
			BufferedImage bi = builder.asBufferedImage();
			Graphics2D gd = bi.createGraphics();
			gd.setFont(new Font(fontName,fontStyle,fontSize));
			gd.setColor(color);
			gd.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
			int length = getTextLength(content);
			int wordLeft = width-fontSize*length;
			int wordTop = height - fontSize;
	        if(left<0){
	        	left = width/2-(fontSize*length)/2;
	        }else if(left>wordLeft){
	        	left = wordLeft;
	        }
	        if(top<0){
	        	top = height/2-fontSize/2;
	        }else if(top>wordTop){
	        	top = wordTop;
	        }
			gd.drawString(content, left, top);
			gd.dispose();
			if(changJPGType){
				ImageIO.write(bi, "jpg",out);
			}else{
				ImageIO.write(bi, fileType,out);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toByteArray();
	}
	/**
	 * 计算文字像素长度
	 * @param content
	 * @return
	 */
	private static int getTextLength(String content){
		int textLength = content.length();  
        int length = textLength;  
        for (int i = 0; i < textLength; i++) {  
            int wordLength = String.valueOf(content.charAt(i)).getBytes(Charset.forName("utf-8")).length;  
            if(wordLength > 1){  
                length+=(wordLength-1);  
            }  
        }
        if(length%2==0){
        	length = length/2;
        }else{
        	length = length/2+1;
        }	
        return length;
	}
	/**
	 * 旋转图片
	 * @param in 图片流
	 * @param rotate 图片旋转角度，正数顺时针，负数逆时针
	 * @param quality 图片质量，1f为原图质量
	 * @param changJPGType 图片是否转换成jpg格式
	 * @return
	 */
	public static byte[] getImgRotate(InputStream in,double rotate,float quality,boolean changJPGType){
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			BufferedImage srcFile = ImageIO.read(in);
			if(srcFile==null){//为null表示非图片
				return null;
			}
			Builder<BufferedImage> builder = Thumbnails.of(srcFile);
			if(changJPGType){
				builder.outputFormat("jpg");
			}
			builder.outputQuality(quality);
			builder.rotate(rotate);
			builder.toOutputStream(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toByteArray();
	}
}
